// FixedBoard class
//

chess_spider.FixedBoard = function( fixedboard_id, title, info, control, loadpgn, gamelist  ) {

	// fixedboard_id
	if( !fixedboard_id ) {
		alert( 'chess_spider configuration error: fixedboard must have fixedboard_id attribute' );
		return;
	}
	this.fixedboard_id = fixedboard_id;
	this.title = title;
	this.info = info;
	this.control = control;
	this.loadpgn = loadpgn;
	this.gamelist = gamelist;
	this.mode = 'normal';

	// this for closure functions
	var fb = this;

	// attach self to fixedboards
	chess_spider.params.fixedboards[this.fixedboard_id] = this;

	// div in which fixedboard sits
	if( !this.dom_div ) {
		this.dom_div = E.div( 	E.div( '.cs__fixedboard_title' ),
					E.form( '.cs__fixedboard_info', 's.display:none', { 'e.click':headerEdit, 'e.submit':nullEvent } ),
					E.div( '.cs__board_container' ),
					E.div( '.cs__fixedboard_panel',
						E.div( '.cs__fixedboard_menu' ),
						E.div( '.cs__fixedboard_options', 's.display:none' ) ) );
						//~E.div( '.cs__fixedboard_loadpgn' ),
						//~E.div( '.cs__fixedboard_control' ),
						//~E.div( '.cs__fixedboard_gamelist' ) ) );
	}

	function headerEdit( e ) {

		// get the mode: pgn, update, new
		function putBack( skiplast ) {

			// drop border and background
			if( hdiv ) {
				hdiv.style.borderStyle = null;
				hdiv.style.borderColor = null;
				hdiv.style.borderWidth = null;
				hdiv.style.backgroundColor = null;
				if( !skiplast ) hdiv.removeChild(hdiv.lastChild);
			}
			
			e.stopPropagation();
			e.preventDefault();
		}

		// if anchor, follow it
		if( e.target.tagName == 'A' ) return;

		// if input, follow it
		if( e.target.tagName == 'INPUT' ) return;

		// get main hdiv
		for( var hdiv=e.target; hdiv.parentNode && hdiv.parentNode.className!='cs__fixedboard_info'; hdiv=hdiv.parentNode );

		// add more headers
		if( hdiv.innerText == '... add more headers' ) {
			var div = E.div( 's.border:1px red solid', 's.backgroundColor:lavender',
					E.i('Your Prompt'), ' ', E.b('your value'),
					E.div( 'Enter New Value for ', E.input( {'s.width':'50%'}, 'Your Prompt' ), E.br(),
					E.input( 'Your Value' ), E.br(),
					E.button( null, 'Save' ), E.button( null, 'Cancel' ) ) );
			hdiv.parentNode.insertBefore(div,hdiv);
			div.getElementsByTagName('INPUT')[0].focus();

			e.stopPropagation();
			e.preventDefault();
			return;
		}

		// get mode and values
		var mode = (hdiv.getElementsByTagName('S').length) ? 'update' : ((hdiv.getElementsByTagName('B').length) ? 'new' : 'pgn' );
		var game = hdiv.cs__getFixedBoard().board.root_mv.game;
		var old_prompt = hdiv.getElementsByTagName('I')[0].innerText;
		var old_value = (hdiv.getElementsByTagName('S').length) ? hdiv.getElementsByTagName('S')[0].innerText : null;
		var new_value = (hdiv.getElementsByTagName('B').length) ? hdiv.getElementsByTagName('B')[0].innerText : null;
		var pgn_value = (new_value) ? old_value : hdiv.childNodes[2].textContent;

		// cancel button
		if( e.target.tagName == 'BUTTON' && e.target.innerHTML == 'Cancel' ) {
			putBack();
			return;
		}

		// save button
		if( e.target.tagName == 'BUTTON' && e.target.innerHTML == 'Save' ) {

			// get inputs
			var input_prompt = (mode=='new') ? hdiv.getElementsByTagName('INPUT')[0].value : old_prompt;
			var input_value = hdiv.getElementsByTagName('INPUT')[((mode=='new')?1:0)].value;

			// save work - not new and no change
			if( mode != 'new' && pgn_value == input_value ) {
				game.headers[old_prompt.replace(/ /g,'')].mode = 'pgn';
				game.headers[old_prompt.replace(/ /g,'')].uvalue = undefined;
				hdiv.innerHTML = '<i>'+old_prompt+'</i> '+pgn_value;
			}
			
			// save work - not new and change
			else if( mode != 'new' && pgn_value != input_value ) {
				console.log( 'headers['+old_prompt.replace(/ /g,'')+'] = '+input_value+', pgn_value='+pgn_value );
				game.headers[old_prompt.replace(/ /g,'')].mode = 'update';
				game.headers[old_prompt.replace(/ /g,'')].uvalue = input_value;
				hdiv.innerHTML = '<i>'+old_prompt+'</i> <s>'+pgn_value+'</s> <b>'+input_value+'</b>';
			}

			// save work - new and deleting
			else if( mode == 'new' && old_prompt &&( input_value == '' || input_prompt == '' ) ) {
				if( old_prompt ) delete game.headers[old_prompt.replace(/ /g,'')];
				hdiv.parentNode.removeChild(hdiv);
				hdiv = null;
			}

			// save work - new and saving
			else if( mode == 'new' && input_prompt != '' && input_value != '' ) {
				if( old_prompt && old_prompt != input_prompt ) delete game.headers[old_prompt.replace(/ /g,'')];
				game.headers[input_prompt] = { 'prompt': input_prompt.replace(/ /g,''), 'uvalue': input_value, 'mode': 'user' };
				/*
				hdiv.innerHTML = '<i>'+input_prompt+'</i> <b>'+input_value+'</b>';
				*/
				hdiv.replaceE( E.i( input_prompt ), ' ',  E.b( input_value ) );
			}

			// done
			putBack( true );
			return;
		}
		
		// ready to expand, but do not if have anchor (cannot edit) or div inside (already expanded)
		if( hdiv.getElementsByTagName('A').length || hdiv.getElementsByTagName('DIV').length ) return;

		// we're here ready to expand the node
		var div = E.div( 's.border:1px red solid', 's.backgroundColor:lavender', 'Enter New Value for ',
			((pgn_value!==null) ? E.i( old_prompt+':' ) : E.input( old_prompt ) ), E.br(),
			E.input( ((new_value!==null)?new_value:pgn_value) ), E.br(),
			E.button( null, 'Save' ), E.button( null, 'Cancel' ) );
		hdiv.appendChild( div );

		// done
		e.stopPropagation();
		e.preventDefault();
	}

	// board attached to fixedboard
	if( !this.board ) {
		this.board = new chess_spider.Board();
		this.board.attach( this.dom_div.getElementsByClassName('cs__board_container')[0]);
	}

	// title
	this.writeTitle();
	this.resetOptions();
	this.display();

	//-console.log( 'fixedboard init: ' + fixedboard_id );
}

// reset options
chess_spider.FixedBoard.prototype.resetOptions = function() {

	// if setup, turn off all unneeded
	if( this.mode == 'setup' && this.board.dom_panel().style.display != 'none' ) {
		this.dom_title().replace( 'Move Pieces until Done' );
		this.board.dom_panel().style.display = 'none';
		this.dom_info().style.display = 'none';
		this.dom_options().style.display = 'none';
		this.dom_loadpgn().style.display = 'none';
		this.dom_gamelist().style.display = 'none';
		this.dom_control().style.display = 'none';
	}

	// turn on relevant options from setup
	else if( this.mode != 'setup' && this.board.dom_panel().style.display == 'none' ) {
		this.writeTitle();
		this.board.dom_panel().style.display = 'table';
		this.dom_options().style.display = 'block';
		// in theory, rest of options should load themselves
	}

	// option area
	var fixedBoard = this;
	var options = {};
	var options_tf = false;

	// set up loadpgn
	if( this.loadpgn ) {
		options['loadpgn'] = { 'label': 'Load PGN',
			'element': E.div( E.i('Enter URL for the ',E.code('PGN'),' to display:'), E.br(),
				E.input( {'placeholder':'http://www.example.com?pgn=12345'} ), E.br(),
				E.button( loadPGN, 'Load New Game(s) Now' ) ) };
		options_tf = true;

		// event func
		function loadPGN(e) { 
			e.stopPropagation();
			e.preventDefault();
			chess_spider.tasks.loadPgnSubmit(e.target);
		};
	}
	else	options['loadpgn'] = null;
	

	// set up control
	if( this.control ) {
		options['control'] = { 'label': 'Control', 
			'element' : E.table( 
				// display font list
				E.tr( E.th('Display:'), E.td( E.form( E.defaults(
						{'name':'cs__disp_font','a.class':'cs__radio','e.click':dispFont,'set_value':chess_spider.params.control.disp_font},
						E.radio('=symbol'), 'Symbol', E.radio('=english'), 'English' ) ) ) ),
				/* offline until working: 
				// board piece
				(( chess_spider.params.piece_imgs['bq'] ) ? E.tr( E.th('Pieces:'), E.td( E.form( E.defaults(
						{'name':'cs__disp_piece','a.class':'cs__radio','e.click':dispPiece,'set_value':chess_spider.params.control.disp_piece},
						E.radio('=img'), 'Image ', E.radio('=div'), 'Font' ) ) ) )
				 : null )
				 */
				 // keyboard
				E.tr( E.th('Keystrokes:'), E.td( E.form( E.defaults(
						{ 'name':'keystrokes',
						  'a.class':'cs__radio',
						  'e.click':useKeystrokes,
						  'set_value': ((chess_spider.params.control.keystrokes)?'on':'off') },
						E.radio('=on'), 'Enable', E.radio('=off'), 'Disable' ) ) ) )
				 ) };
		// event funcs
		function dispFont(e) {
			chess_spider.params.control.disp_font = e.target.ancestorByTagName('FORM').getRadio(e.target.name);
			chess_spider.MoveList.movelists().forEach( function(ml) { ml.redisplay(); } );
			chess_spider.Board.boards().forEach( function(bd) { bd.writeLastMove(); } );
		}
		function dispPiece(e) {
			chess_spider.params.control.disp_piece = e.target.ancestorByTagName('FORM').getRadio(e.target.name);
			chess_spider.Board.boards().forEach( function(bd) { bd.userJump(bd.cur_mv); } );
		}
		function useKeystrokes(e) {
			chess_spider.params.control.keystrokes = (e.target.ancestorByTagName('FORM').getRadio(e.target.name)=='on');
		}
		options_tf = true;
	}
	else	options['control'] = null;

	// gamelist
	if( this.control && chess_spider.state.game_arr.length > 1 ) {
		options['gamelist'] = { 'label': 'Game List', 
			'element': ( (function() { var arr = []; for( i=0; i<chess_spider.state.game_arr.length; i++ ) {
						arr.push( E.a( 'game', switchGame, 
						{ 'title':"DoubleClick to Export this Game's PGN",
						's.fontWeight':((chess_spider.state.cur_bd && chess_spider.state.cur_bd.root_mv.game.idx == i )?'bold':'normal'), 
						'e.dblclick': exportGame, 'idx':i }, chess_spider.state.game_arr[i].title() ) ),
						arr.push( E.br() );
					} return arr; } )() ) };

		options_tf = true;
	}
	else	options['gamelist'] = null;

	// option pane
	this.dom_options().replaceE( null );
	if( options_tf ) {
		options['none'] = { 'label': 'n/a', 'element': E.text('we should not see this') };
		this.dom_menu().replaceE( " \u00a0 ",
				(function() { arr = []; for( id in options ) if( options[id] ) {
						arr.push( E.a( id, setOption, options[id].label ) );
						arr.push( " \u00a0 " );
				} return arr; })() );
	}

	// first option
	if( options_tf && options.gamelist ) setOption('gamelist');
	else if( options_tf ) setOption('none');

	// closure / util
	function switchGame( e ) {
		alert( 'switch idx: ' + e.target.getAttribute('idx') );

		if( e ) e.stopPropagation();
		if( e ) e.preventDefault();
	}
	function exportGame( e ) {
		alert( 'export idx: ' + e.target.getAttribute('idx') );

		if( e ) e.stopPropagation();
		if( e ) e.preventDefault();
	}
	function setOption( p_id ) {

		var e = window.event;

		// if coming from anchor click, arg[0] will be event
		if( e == p_id ) p_id = this.href.match(/([a-z]*)$/)[1];

		// bold/unbold options
		var hrefs = fixedBoard.dom_menu().getElementsByTagName('a');
		for( var i=0; i<hrefs.length; i++ ) {
			var id = hrefs[i].href.match(/([a-z]*)$/)[1];
			hrefs[i].style.fontWeight = ( id == p_id ) ? 'bold' : 'normal';
			if( id == 'none' ) continue;
		}

		// set element content
		fixedBoard.dom_options().replaceE( options[p_id].element );
		fixedBoard.dom_options().displayToggle( (p_id!='none') );

		// if fixedboard, reposition
		fixedBoard.reposition( fixedBoard.dom_options() );

		if( e ) e.stopPropagation();
		if( e ) e.preventDefault();
	}
}

// reset gamelist on all fixedboards
chess_spider.FixedBoard.resetAllOptions = function() {
	for( var id in chess_spider.params.fixedboards )
	if( chess_spider.params.fixedboards[id]['fixedboard_id'] != undefined ) {
		chess_spider.params.fixedboards[id].resetOptions();
		if( chess_spider.params.fixedboards[id].board && chess_spider.params.fixedboards[id].board.cur_mv ) {
			chess_spider.params.fixedboards[id].board.userJump(chess_spider.params.fixedboards[id].board.cur_mv);
		}
	}
}


// initialize fixedboard from array
chess_spider.FixedBoard.initAll = function() {

	// new fixedboards must be added with new FixedBoard
	for( var board_id in chess_spider.params.fixedboards ) {

		// only interested in set attributes
		if( typeof board_id != 'string' || typeof chess_spider.params.fixedboards[board_id] != 'object' ) continue;

		// proper fixedboard - it will attach itself to chess_spider.params.fixedboards
		new chess_spider.FixedBoard(
			board_id,
			chess_spider.params.fixedboards[board_id].title,
			chess_spider.params.fixedboards[board_id].info,
			chess_spider.params.fixedboards[board_id].control,
			chess_spider.params.fixedboards[board_id].loadpgn,
			chess_spider.params.fixedboards[board_id].gamelist );
	}
}

// get all fixedboards in document
chess_spider.FixedBoard.fixedboards = function() {

	var result_arr = new Array();

	// all board containers in document by class
	var dom_arr = document.getElementsByClassName('cs__fixedboard_container');
	for( var i=0; i<dom_arr.length; i++ )
	if( dom_arr[i].id && chess_spider.params.fixedboards[dom_arr[i].id] ) {
		result_arr.push( chess_spider.params.fixedboards[dom_arr[i].id] );
	}

	return result_arr;
}

// helper for display
chess_spider.FixedBoard.display = function( fixedboard_id, game, action ) {
	chess_spider.params.fixedboards[fixedboard_id].display( game, action );
}

// display
chess_spider.FixedBoard.prototype.display = function( game ) {

	// attach to doc if not attached by appending children of dom_div to element, then remapping dom_id
	if( this.dom_div != document.getElementById(this.fixedboard_id) ) {
		document.getElementById(this.fixedboard_id).parentNode.replaceChild( this.dom_div, document.getElementById(this.fixedboard_id) );
		this.dom_div.id = this.fixedboard_id;
		this.dom_div.className = 'cs__fixedboard_container';
	}

	// new game
	if( !game ) {
		this.board.display( null );
	}
	else if( !this.board.root_mv || this.board.root_mv.game != game ) {
		this.board.display( game.root_mv );
	}

	// reposition ourself
	this.reposition();
}

// reposition fixedboard
// source: comment, board
// diplayed: true/false whether component was displayed (vs hidden)
chess_spider.FixedBoard.prototype.repositionSecondLastDomSource = null;
chess_spider.FixedBoard.prototype.repositionLastDomSource = null;
// sources: board, info, comment, (how to do fixedboard options, including gamelist)
chess_spider.FixedBoard.prototype.reposition = function( dom_source ) {

	// must have id and size before we reposition
	if( !this.dom_div || !this.dom_div.clientHeight ) return;

	// last source
	var displayed = null;
	if( dom_source ) displayed = ( dom_source.style.display != 'none' );
	if( dom_source && displayed && dom_source != this.repositionLastDomSource ) {
		if( this.repositionSecondLastDomSource != this.repositionLastDomSource && this.repositionLastDomSource ) {
			this.repositionSecondLastDomSource = this.repositionLastDomSource;
		}
		this.repositionLastDomSource = dom_source;
	}
	if( this.repositionLastDomSource == dom_source && !displayed ) this.repositionLastDomSource = null;
	if( this.repositionSecondLastDomSource == dom_source && !displayed ) this.repositionSecondLastDomSource = null;

	// console.log( 'fixedboard.reposition( '+((dom_source)?dom_source.className:null)
		// + '('+((this.repositionLastDomSource)?this.repositionLastDomSource.tagName:null)+'), '
		// + displayed+' )' );

	// part to be centered, parent container
	var dom_pnt = this.dom_div.parentNode;

	// resizes - order of priority to be seen
	// board iteself, header, panel_options
	// todo: add fixedboard options and gamelist
	var dom_sources = [ this.board.dom_table(),
			this.board.dom_panel_options(),
			this.dom_info(),
			this.dom_options() ];

	// open last dom and table if possible
	if( !displayed ) {

		// last dom
		if( this.repositionLastDomSource && this.repositionLastDomSource.style.display == 'none'
		&&  this.dom_div.clientHeight+this.repositionLastDomSource.clientHeight < dom_pnt.clientHeight ) {
			this.repositionLastDomSource.displayToggle(true);
		}
		// second last dom
		if( this.repositionSecondLastDomSource && this.repositionSecondLastDomSource.style.display == 'none'
		&&  this.dom_div.clientHeight+this.repositionSecondLastDomSource.clientHeight < dom_pnt.clientHeight ) {
			this.repositionSecondLastDomSource.displayToggle(true);
		}
		// board
		if( this.board.dom_table().style.display == 'none'
		&&  this.dom_div.clientHeight+this.board.dom_table().clientHeight < dom_pnt.clientHeight ) {
			this.board.dom_table().displayToggle(true);
		}
	}

	// too tall - reduce size if not last dom
	if( this.dom_div.clientHeight > dom_pnt.clientHeight )
	for( var i=dom_sources.length-1; i>=0; i-- ) {
		if( this.dom_div.clientHeight > dom_pnt.clientHeight
		&&  dom_sources[i] != this.repositionLastDomSource
		&&  dom_sources[i] != this.repositionSecondLastDomSource
		&&  dom_sources[i].style.display != 'none' ) {
			dom_sources[i].style.display = 'none';
		}
	}

	// shrink second last and last dom if necessary
	if( this.dom_div.clientHeight > dom_pnt.clientHeight
	&&  this.repositionSecondLastDomSource && dom_source != this.repositionSecondLastDomSource ) {
		this.repositionSecondLastDomSource.style.display = 'none';
	}
	if( this.dom_div.clientHeight > dom_pnt.clientHeight
	&&  this.repositionLastDomSource && dom_source != this.repositionLastDomSource ) {
		this.repositionLastDomSource.style.display = 'none';
	}
	
	// center fixedboard
	var top = (this.dom_div.clientHeight>=dom_pnt.clientHeight) ? 0 : (dom_pnt.clientHeight - this.dom_div.clientHeight) / 2;
	this.dom_div.style.top = (this.dom_div.clientHeight>=dom_pnt.clientHeight) ? 0 : (dom_pnt.clientHeight - this.dom_div.clientHeight) / 2;
}


// write title && info for fixedboard
chess_spider.FixedBoard.prototype.writeTitle = function() {

	//-console.log( 'writeTitle: ' + ((this.board.root_mv)?this.board.root_mv.id:'null') );
	
	// this for closure funcs
	var fb = this;

	// title
	if( this.title === false )			this.dom_title().replaceE( '(you should not see this)' );
	else if( typeof this.title == 'string' )	this.dom_title().replaceE( this.title );
	else if( !this.board || !this.board.root_mv )	this.dom_title().replaceE( '(to be determined by game)' );
	else {
		this.dom_title().replaceE( E.a( 'toggle', infoToggle, "  \u2297" ), ((this.board.root_mv)?this.board.root_mv.game.title():'Unknown Game') );
	}

	function infoToggle( e ) {

		// toggle info
		fb.dom_info().displayToggle();

		// re-center
		fb.reposition( fb.dom_info() );

		e.stopPropagation();
		e.preventDefault();
	}


	// info
	var buf = '';
	if( !this.board.root_mv ) this.dom_info().replaceE( '(to be determined by game)' );
	else {
		this.dom_info().replaceE();
		// attach source if not there
		if( this.board.root_mv.game.headerValue('Source')==undefined && this.board.root_mv.game.pgn_url ) {
			this.dom_info().appendE( E.div( E.i('Source '), E.a( this.board.root_mv.game.pgn_url, null, this.board.root_mv.game.pgn_url.split('/')[2] ) ) );
		}
		// attach each header
		for( var h in this.board.root_mv.game.headers ) 
		if( typeof(this.board.root_mv.game.headers[h]) == 'object' ) {
			var div = E.div( E.i(h.replace(chess_spider.regx.upperspace,'$1 $2') ), ' ' );
			if( this.board.root_mv.game.headerValue(h).substr(0,4)=='http' ) 
				div.appendE( E.a( this.board.root_mv.game.headerValue(h), null, {'target':'_blank'},
					this.board.root_mv.game.headerValue(h).split('/')[2] ) ); 
			else if( this.board.root_mv.game.headerMode(h) == 'update' ) 
				div.appendE( E.s( this.board.root_mv.game.headers[h].value ), ' ', E.b( this.board.root_mv.game.headers[h].uvalue ) );
			else if( this.board.root_mv.game.headerMode(h) == 'new' )
				div.appendE( E.b( this.board.root_mv.game.headers[h].uvalue ) );
		       	else div.appendE( this.board.root_mv.game.headers[h].value );
			this.dom_info().appendChild( div );
		}
		// option
		if( chess_spider.params.control.interactive ) this.dom_info().appendE( E.div( 's.textAlign:right', '`... add more headers' ) );
	}
}

// attach board to dom
chess_spider.FixedBoard.prototype.setMove = function( move ) {
	this.board.setMove( move );
	this.writeTitle();
}

// FixedBoard helpers
chess_spider.FixedBoard.prototype.dom_title = function() { return this.dom_div.getElementsByClassName('cs__fixedboard_title')[0] };
chess_spider.FixedBoard.prototype.dom_info = function() { return this.dom_div.getElementsByClassName('cs__fixedboard_info')[0] };
chess_spider.FixedBoard.prototype.dom_menu = function() { return this.dom_div.getElementsByClassName('cs__fixedboard_menu')[0]; }
chess_spider.FixedBoard.prototype.dom_options = function() { return this.dom_div.getElementsByClassName('cs__fixedboard_options')[0]; }
chess_spider.FixedBoard.prototype.dom_loadpgn = function() { return this.dom_div.getElementsByClassName('cs__fixedboard_loadpgn')[0]; }
chess_spider.FixedBoard.prototype.dom_gamelist = function() { return this.dom_div.getElementsByClassName('cs__fixedboard_gamelist')[0]; }
chess_spider.FixedBoard.prototype.dom_control = function() { return this.dom_div.getElementsByClassName('cs__fixedboard_control')[0]; }

// setup
chess_spider.FixedBoard.setupInit = function( setup ) {

	// must have default fixedboard
	if( !chess_spider.params.fixedboard_dflt ) return false;
	var fb = chess_spider.params.fixedboards[chess_spider.params.fixedboard_dflt];
	var tbl = fb.board.dom_table();
	fb.board.setCur( true );

	// if we're already doing this
	if( setup && fb.mode == 'setup' ) return false;

	// setup mode
	if( setup ) {

		// add a row to bottom for white
		var tr = document.createElement('tr');
		for( var file='a'; file<='h'; file=chess_spider.util.incFile(file) ) {
			var td = document.createElement('td');
			td.className = 'cs__wSet';
			td.setAttribute('sq',file+'0');
			tr.appendChild(td);
		}
		tbl.appendChild(tr);
		fb.board.set( 'a0', 'w', ' ', true );
		fb.board.set( 'b0', 'w', 'p', true );
		fb.board.set( 'c0', 'w', 'n', true );
		fb.board.set( 'd0', 'w', 'q', true );
		fb.board.set( 'e0', 'w', 'k', true );
		fb.board.set( 'f0', 'w', 'b', true );
		fb.board.set( 'g0', 'w', 'r', true );
		fb.board.set( 'h0', 'w', ' ', true );

		// add a row to top for black
		var tr = document.createElement('tr');
		for( var file='a'; file<='h'; file=chess_spider.util.incFile(file) ) {
			var td = document.createElement('td');
			td.className = 'cs__bSet';
			td.setAttribute('sq',file+'9');
			tr.appendChild(td);
		}
		tbl.insertBefore(tr,tbl.getElementsByTagName('tr')[0]);
		fb.board.set( 'a9', 'b', ' ', true );
		fb.board.set( 'b9', 'b', 'p', true );
		fb.board.set( 'c9', 'b', 'n', true );
		fb.board.set( 'd9', 'b', 'q', true );
		fb.board.set( 'e9', 'b', 'k', true );
		fb.board.set( 'f9', 'b', 'b', true );
		fb.board.set( 'g9', 'b', 'r', true );
		fb.board.set( 'h9', 'b', ' ', true );

		// add controls
		var div = E.div( 's.whiteSapce:nowrap',
				E.button( 's.width:33%', save, 'Done / Save' ),
				E.button( 's.width:18%', clear, 'Clear' ),
				E.button( 's.width:18%', cancel, 'Cancel' ),
				' First:', E.select( {'value':'1w'},
					{'iterator': { 'from': 1, 'thru': 40, 'function': function(i) { return [ E.option(i+'w'), E.option(i+'b') ]; } } } ) );
		tbl.parentNode.insertBefore( div, tbl.nextSibling );


		// attach draggable to all pieces (pieces have drag start attached on creation)
		var tds = tbl.getElementsByTagName('td');
		for( var i=0; i<tds.length; i++ ) {
			tds[i].firstChild.draggable = true;
		}

		// done - reshow
		fb.mode = 'setup';
		fb.resetOptions();
		fb.reposition();
	}

	// if not setup, return with new board
	else {
		//-console.log( 'virgin board' );
		done( window.event, true );
	}

	fb.reposition( fb.board.dom_table() );
	return false;


	// closure funcs - - - - - - -
	//
	function clear( e ) {
		for( var rank=1; rank<=8; rank=chess_spider.util.incRank(rank) )
		for( var file='a'; file<='h'; file=chess_spider.util.incFile(file) ) {
			fb.board.set( file+rank, 'w', ' ', true );
			fb.board.square(file+rank).firstChild.draggable = true;
			fb.board.square(file+rank).addEventListener('drag',chess_spider.events.drag,true);
		}
		e.preventDefault();
	}
	function save( e ) { done( e, true ); }
	function cancel( e ) { done( e, false ); }
	function done( e, save ) {

		// saving
		if( save ) {

			// setup mode - get psnt and first move
			if( fb.mode == 'setup' ) {

				// grap pieces into game orig_pstn
				orig_pstn = '';
				for( var rank=1; rank<=8; rank=chess_spider.util.incRank(rank) )
				for( var file='a'; file<='h'; file=chess_spider.util.incFile(file) ) {
						orig_pstn += fb.board.get(file+rank);
				}
				console.log( 'pstn="'+orig_pstn+'"' );
				
				// orig move
				var orig_mv = e.target.parentNode.parentNode.getElementsByTagName('select')[0].value;
				console.log( 'mv="'+orig_mv+'"' );

				pgn +=	"[OrigPstn \""+orig_pstn+"\"]\n"
					+ "[FirstMove \""+orig_mv+"\"]\n";
			}

			// add as new game
			var game = new chess_spider.Game( 
				  '[Title "User Created Game"]\n'
				+ '[Author "'+ ((chess_spider.state.user.login)
							? chess_spider.state.user.login+'@chess-spider.com'
							: 'Unknown Genius' )+'"]\n'
				+ '[CreateDate "'+(new Date()).format()+'"]\n',
				null, 'user' );

			// display
			game.display( chess_spider.params.movelist_dflt, chess_spider.params.fixedboard_dflt );
		}

		// put board back
		if( fb.mode == 'setup' ) {
			tbl.removeChild(tbl.rows[9]);
			tbl.removeChild(tbl.rows[0]);
			tbl.parentNode.removeChild( tbl.nextSibling );

			// re-straighten fb
			fb.mode = 'normal';
		}

		// straigten up
		fb.resetOptions();
		fb.reposition();

		// get user there
		if( save ) {
			nonblockAlert( 'Drag Pieces to create your game' );
			game.setCur();
		}
	}
}
